package com.fengwk.user.service.impl;

import java.util.Collection;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fengwk.support.function.Return;
import com.fengwk.support.util.CollectionUtils;
import com.fengwk.support.util.StringUtils;
import com.fengwk.user.face.model.Permission;
import com.fengwk.user.face.model.Role;
import com.fengwk.user.service.PermissionService;
import com.fengwk.user.service.RoleService;
import com.fengwk.user.service.ValidationService;

@Service
public class ValidationServiceImpl implements ValidationService {

	@Autowired
	private RoleService roleService;
	@Autowired
	private PermissionService permissionService;
	
	@Override
	public boolean validationRoles(Long userId, Collection<String> roles) {
		if (CollectionUtils.isNotBlank(roles)) {
			List<Role> roleList = roleService.listRoleByUserId(userId);
			if (CollectionUtils.isNotBlank(roleList)) {
				for (String role: roles) {
					if (!startContains(
							roleList, role, roleBuf -> roleBuf.getRole())) {
						return false;
					}
				}
			} else {
				return false;
			}
		}
		return true;
	}

	@Override
	public boolean validationPermissions(Long userId, Collection<String> permissions) {
		if (CollectionUtils.isNotBlank(permissions)) {
			List<Permission> permissionList = permissionService.listPermissionByUserId(userId);
			if (CollectionUtils.isNotBlank(permissionList)) {
				for (String permission: permissions) {
					if (!startContains(
							permissionList, permission, permissionBuf -> permissionBuf.getPermission())) {
						return false;
					}
				}
			} else {
				return false;
			}
		}
		return true;
	}
	
	private <E> boolean startContains(Collection<E> collections, String tar, Return.Params1<String, E> getSelf) {
		for (E e: collections) {
			String self = getSelf.apply(e);
			if (StringUtils.isNotBlank(self)) {
				self = self.replace(" ", "").replaceAll(":\\*$", "");
				if (tar.startsWith(self)) {
					return true;
				}
			}
		}
		return false;
	}

}
